const config = require("./config");
const fs =require('fs');
const compressFile = require("./compressFile");
const sshServer = require("./ssh");
const uploadFile = require("./uploadFile");
const {runCommand,runScript} = require("./handleCommand");
const ora = require('ora');
const chalk = require('chalk');
const log = console.log;
// 主程序
async function main() {
  try {
    // 运行打包命令
    await runScript('npm run build')
    log(chalk.blue("请确保文件解压后为dist目录!!!"));
    const { name, targetFile, compressedFiles, releaseDir, deployDir, ssh } =
      config; // 所选部署项目的配置信息
    const compressedFilesName = __dirname + "/../../" + compressedFiles; // 待压缩文件
    const localFile = __dirname + "/../../" + targetFile; // 待上传本地文件
    await compressFile(compressedFilesName, localFile); //压缩
    const SSH = await sshServer(ssh); // 连接
    await uploadFile(SSH, config, localFile); // 上传
    await runCommand(SSH, "unzip " + targetFile, deployDir); // 解压
    await runCommand(SSH, "mv dist " + releaseDir, deployDir); // 修改文件名称
    await runCommand(SSH, "rm -f " + targetFile, deployDir); // 删除
    fs.unlink(localFile,(err)=>{log(chalk.red(err))}) // 删除本地压缩包
    log(chalk.green("✨ 项目部署完成"));
  } catch (err) {
    log(chalk.red("部署过程出现错误！", err));
  } finally {
    process.exit();
  }
}
// run main
main()